<template>
	<!-- class="bgMinor2" :style="{minHeight:`${windowHeight * 2}rpx`,height:'auto'}" -->
	<!-- <view> -->
	<!-- v-model="data.list" @query="queryList" :use-page-scroll="true" -->
	<div class="gundongtiao">
		<z-paging ref="refPaging">
			<template #top>
				<!-- bgColor="transparent" -->
				<uv-navbar :fixed="false" placeholder safeAreaInsetTop bgColor="#eee">
					<template v-slot:left>
						<view class=""></view>
					</template>
					<template v-slot:center>
						<view class="Flex">
							<uv-image src="/static/images/logo2.png" width="42px" height="35px"></uv-image>
						</view>
					</template>
				</uv-navbar>
			</template>
		
			<view class="bgMinor2 heightAuto pd-24">
				<view class="flex mt-61">
					<view class="bgWhite pt-30 pd-24 flex flex-1 relative mr-42 radius-16"
						@click.stop="addOpen('/pages/homepage/rehandling?tab=1')">
						<uv-image src="/static/images/huanzhuang.png" width="86rpx" height="95rpx"></uv-image>
						<view class="flex renClass">
							<uv-image src="/static/images/nan.png" width="177rpx" height="190rpx"></uv-image>
						</view>
					</view>
		
					<view class="bgWhite pt-30 pd-24 flex flex-1 relative radius-16"
						@click.stop="addOpen('/pages/homepage/customization?tab=2')">
						<uv-image src="/static/images/dingzhi.png" width="86rpx" height="95rpx"></uv-image>
						<view class="flex hidden renClass radius-16" style="width: 219rpx; height: 190rpx">
							<view class="flex renNvClass">
								<uv-image src="/static/images/nv.png" width="219rpx" height="190rpx"></uv-image>
							</view>
						</view>
					</view>
				</view>
		
				<view class="bgWhite mt-46 plr-24 pt-20 pb-40 radius-16">
					<view class="">
						<view class="flex">
							<view class="size-40 color-blue1 weight-6">推荐</view>
							<view class="size-24 color-black2 flex">
								<view class="mr-8" @click.stop="addOpen('/pages/homepage/myOneClickChange?name=4')">
									全部</view>
								<view class="flex">
									<uv-icon name="arrow-right" :color="m_icon" size="24rpx"></uv-icon>
								</view>
							</view>
						</view>
						<view class="mt-20 flex1 XScroll">
							<!-- <view class="wd10-28 height-397 bgMinor2 radius-16 mr-20 nohuanhang">大萨达撒多撒撒多大萨达撒多撒其味无穷二</view> -->
							<view class="">
								<!-- <uv-image src="/static/images/nv.png" width="280rpx" height="394rpx"></uv-image> -->
							</view>
							<view class="itemClass " style="display: flex;" v-if="dataInfo.recommend.length > 0 ">
								<view @click="addOpen(`/pages/mine/veinManDetails?flag=hot2&user=`+item.id)"
									v-for="(item, index) in dataInfo.recommend" :key="index"
									class="width-273 height-389 bgMinor2 radius-16"
									style="overflow: hidden;display: flex;justify-content: center;border-radius: 15rpx;height: 389rpx;">
									<uv-image :src=" item.imgUrl" width="100%" height="100%"></uv-image>
		
		
								</view>
							</view>
							<view class=" mt-40" v-else style="width: 100%;">
								<view
									style="font-size: 30rpx;width: 100%;text-align: center;  color: rgb(204, 204, 204);height: 25vh;display: flex;align-items: center;justify-content: center;width: 100%;">
									暂 无 数 据</view>
							</view>
						</view>
					</view>
		
				</view>
				<view class="bgWhite mt-46 plr-24 pt-20 pb-40 radius-16">
					<view class="">
						<view class="flex">
							<view class="size-40 color-blue1 weight-6">热门展示</view>
							<view class="size-24 color-black2 flex">
								<view class="mr-8" @click.stop="addOpen('/pages/homepage/myOneClickChange?name=5')">
									全部</view>
								<view class="flex">
									<uv-icon name="arrow-right" :color="m_icon" size="24rpx"></uv-icon>
								</view>
							</view>
						</view>
						<view class="mt-20 flex1 XScroll">
							<!-- <view class="wd10-28 height-397 bgMinor2 radius-16 mr-20 nohuanhang">大萨达撒多撒撒多大萨达撒多撒其味无穷二</view> -->
							<view class="">
								<!-- <uv-image :src=" baseURL + '/preview/'  +item.imgUrl" width="280rpx" height="394rpx"></uv-image> -->
							</view>
							<view class="itemClass " style="display: flex;" v-if="dataInfo.getPopularList.length > 0 ">
		
								<view @click="addOpen(`/pages/mine/veinManDetails?flag=hot2&user=`+item.id)"
									v-for="(item, index) in dataInfo.getPopularList" :key="index"
									class="width-273 height-389 bgMinor2 radius-16"
									style="overflow: hidden;display: flex;justify-content: center;border-radius: 15rpx;height: 389rpx;">
		
									<uv-image :src="  item.synthesisImg" width="100%" height="100%"></uv-image>
								</view>
							</view>
							<view class=" mt-40" v-else style="width: 100%;">
								<view
									style="font-size: 30rpx;width: 100%;text-align: center;  color: rgb(204, 204, 204);height: 25vh;display: flex;align-items: center;justify-content: center;width: 100%;">
									暂 无 数 据</view>
							</view>
						</view>
					</view>
		
				</view>
		
				<uv-popup ref="popupUseRef" mode="bottom" :close-on-click-overlay="false" round="16rpx">
					<view class="info-container">
						<view class="title">获取你的昵称、头像</view>
						<view class="desc">
							获取用户头像、昵称，主要用于向用户提供其持有的用户中心头像，此项操作如您选择拒绝或上传本地头像，我们将使用您的相机、相册权限，感谢您的理解。
						</view>
						<view class="item">
							<label class="label">头像</label>
							<view class="avatar-container">
								<button v-if="!avatarUrl" @click="uploadImagea" class="choose-avatar-btn">选择头像</button>
								<image v-else :src="avatarUrl"  mode="aspectFit" class="avatar"></image>
								
							</view>
						</view>
						<view class="item">
							<label class="label">昵称</label>
							<input v-model="nickName" type="nickname" placeholder="请输入昵称" class="nickname-input" />
						</view>
						<button @click="saveInfo" class="save-btn">保存</button>
					</view>
				</uv-popup>
			</view>
		</z-paging>
		
	</div><!-- </view> -->
</template>

<script setup lang="ts">
	import { onShow, onLoad } from '@dcloudio/uni-app';
	import { reactive, ref, onMounted } from 'vue';

	import { getWindowHeight } from '@/pages/util/getHeight';
	import { addOpen, loggedIn, addOpenTab } from '@/pages/util/hooks';
	import useLoginStore from '@/pinia-store/userInfoStore';
	import { get, post, baseConfig } from '@/utils/request';
	import { baseURL, } from '@/utils/config.ts';
	import store from '@/store';
	const useLogin = useLoginStore();
	const windowHeight = getWindowHeight();
	const refPaging = ref(null);
	const isPopupVisible = ref(true)
	/** @name 数据 */
	const dataInfo = reactive({
		username: '',
		password: '',
		captcha: '',
		list: [],
		recommend: [],
		getPopularList: []
	});
	const listFun = async () => {
		try {
			const response = await get<{
				code : number;
				result : any;
				type : Number
			}>('material/getList', { type: 0 });
			if (response.code == 200) {
				console.log(response)
				dataInfo.recommend = response.result.records
			}

		} catch (error) {
			console.error(error);
		}
	};
	const getPopularListFun = async () => {
		try {
			const response = await get<{
				code : number;
				result : any;
				type : Number
			}>('customized/getPopularList', { type: 0 });
			if (response.code == 200) {
				console.log(response)
				dataInfo.getPopularList = response.result.records
			}
		} catch (error) {
			console.error(error);
		}
	};
	const code = ref('')
	const submitData = async () => {
		try {
			// 获取 code
			const loginRes = await uni.login({
				provider: 'weixin',
			});
			code.value = loginRes.code

			// 获取用户信息
			// const userInfoRes = await uni.getUserInfo({
			// 	provider: 'weixin',
			// 	lang: 'zh_CN',
			// });
			// getUserFun(loginRes.code, userInfoRes.userInfo.avatarUrl, userInfoRes.userInfo.nickName)

			// uni.setStorageSync('avatarUrl', userInfoRes.userInfo.avatarUrl);
			// uni.setStorageSync('username', userInfoRes.userInfo.nickName);

			// // userInfo.value = userInfoRes.userInfo;
			// console.log('获取到的用户信息:', userInfoRes.userInfo);

		} catch (error) {
			console.error('获取 code 或用户信息时出错:', error);
		}
	};
	// 直接请求登录
	const getUserFun = async (code : any, avatarUrl : any, realname : any) => {
		try {

			const data = {
				avatarUrl: avatarUrl,
				signature: code,
				inviteCode: "1"
			}

			uni.request({
				data: data,
				// url: 'http://121.40.122.64:8183/ai/sys/weCatlogin', // 替换为实际的 API 地址
				url: 'https://www.mrxc915.com/ai/sys/weCatlogin', // 替换为实际的 API 地址
				
				method: 'POST',
				success: (res) => {
					const responses = res.data.result;
					console.log('提交结果:', responses);
					uni.setStorageSync('Token', res.data.result.token);
					// sessionStorage.setItem('Token', res.data.result.token);
					dataInfo.userInfoObj = responses.userInfo


					// dataInfo.userInfoObj.usernames = responses.userInfo.username
					// dataInfo.userInfoObj.username = responses.userInfo.username.substring(0, 5)
					// console.log('responses.userInfo')
					// console.log(dataInfo.userInfoObj)
					store.commit('setIsMember', responses.userInfo.isMember)
					// "isMember":"是否会员  0：不是 1：是",
					store.commit('setisMerchant', responses.userInfo.isMerchant)
					// "isMerchant":"是否商家 0：不是 1：是",
					uni.setStorageSync('userData', JSON.stringify(responses.userInfo));

					listFun()
					getPopularListFun()
				},
				fail: (err) => {
					console.error('请求失败:', err);
				}
			});
			// console.log(data)



		} catch (error) {
			// 处理错误
		}
	}


	// 弹出确认框
	const popupUseRef = ref(null);


	/** @name 使用弹框变化事件 */
	async function usePopup(e) {
		console.log('usePopup', e);
		if (e.show) {
			// #ifdef H5
			// uni.hideTabBar(); // 隐藏tabbar
			// #endif
		} else {
			// #ifdef H5
			// uni.showTabBar(); // 显示tabbar
			// #endif
		}
	}
	const avatarUrl = ref('');
	// 存储昵称
	const nickName = ref('');
	const preventClose = (e : any) => {
		e.preventDefault(); // 尝试阻止默认关闭行为
		popupUseRef.value?.open();
	};
	// 处理头像选择事件
	const uploadImagea = (e : any) => {
		console.log(e)
		
		uni.chooseImage({
			count: 1, // 默认9
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: (res) => {
				console.log('上传文件')
				console.log(res.tempFiles)
				uni.uploadFile({
					url: baseConfig.baseURL + 'sys/common/upload', // 替换为实际的上传接口地址
					filePath: res.tempFilePaths[0],
					name: 'file',
					header: {
						'X-Access-Token': uni.getStorageSync('Token')
					},
					formData: {
						// 这里可以添加其他表单数据
						file: res.tempFiles[0],
					},
					success: (uploadRes) => {
						let data = JSON.parse(uploadRes.data)
						avatarUrl.value =  data.message
						
						console.log(avatarUrl.value)
						console.log('上传成功', data);
					},
					fail: (err) => {
						console.error('上传失败', err);
					}
				});
			}
		});
		// uni.request({
		//     url: avatarUrl.value,
		//     responseType: 'arraybuffer',
		//     success: (res) => {
		//       if (res.statusCode === 200) {
		//         const fileStream = res.data as ArrayBuffer;
		//         console.log('已成功获取文件流:', fileStream);
		//         // 在这里可以进行后续操作，如上传文件流到服务器
		//       } else {
		//         console.error('请求失败，状态码:', res.statusCode);
		//       }
		//     },
		//     fail: (err) => {
		//       console.error('请求出错:', err.errMsg);
		//     }
		//   });
		// const tempFilePath =avatarUrl.value;
		// // 获取文件系统管理器
		// const fs = uni.getFileSystemManager();
		// // 读取文件的二进制流
		// fs.readFile({
		// 	filePath: tempFilePath,
		// 	encoding: 'binary',
		// 	success: (readRes) => {
		// 		const binaryData = readRes.data;
		// 		console.log('成功获取二进制流', binaryData);
		// 	},
		// 	fail: (readErr) => {
		// 		console.error('读取文件失败', readErr);
		// 	}
		// });

	};
	// const onChooseavatar = (e) => {
	// 	if (uni.getUserProfile) {
	// 		uni.getUserProfile({
	// 			desc: "获取用户信息仅用于展示",
	// 			success(res) {
	// 				console.log(res);
	// 				console.log("用户点击允许");
	// 				console.log("用户信息", that.userInfo);
	// 				const userInfo = res.userInfo;
	// 				//性别 0：未知、1：男、2：女

	// 			},
	// 			fail(error) {
	// 				console.log("用户未授权", error);
	// 				// uni.showToast({
	// 				//   title: "登录失败",
	// 				//   duration: 3000,
	// 				//   icon: "none",
	// 				// });
	// 			},
	// 		});
	// 	};
	// }

	const saveInfo = () => {

		if (!nickName.value) {
			uni.showToast({ title: '昵称不能为空', icon: 'none' });
			return;
		}
		// 此处可扩展为调用后端接口保存数据
		console.log('保存的头像:', avatarUrl.value, '昵称:', nickName.value);
		saveInfoFun()
		// uploadImages()
	};

	async function uploadImage() {

		uni.getFileSystemManager().readFile({
			filePath: avatarUrl.value,
			encoding: 'binary',
			success: (res) => {
				// 获取图片的二进制数据
				const binaryData = res.data;
				console.log('---pppp')
				console.log(binaryData)
				const newFilePath = `${uni.env.USER_DATA_PATH}/new_image.jpg`;
				uni.getFileSystemManager().writeFile({
					filePath: newFilePath,
					data: binaryData,
					encoding: 'binary',
					success: (val) => {
						console.log('文件保存成功:', val);
					},
					fail: (err) => {
						console.error('保存文件失败:', err);
					}
				});
				// 生成新的文件路径
				// uploadImages(newFilePath)
			},
			fail: (err) => {
				console.error('读取文件失败:', err);
			}
		});
	}
	async function uploadImages() {
		let data =
			// {
			// 	path: "http://tmp/ykKu5NAn0ATa8c0181df1c9830ce2d11ed9ee8ce00f2.png",
			// 	size: 63576,
			// 	constructor: (...)
			// 	hasOwnProperty: (...)
			// 	isPrototypeOf: (...)
			// 	propertyIsEnumerable: (...)
			// 	toLocaleString: (...)
			// 	toString: (...)
			// 	valueOf: (...)
			// 	__defineGetter__: (...)
			// 	__defineSetter__: (...)
			// 	__lookupGetter__: (...)
			// 	__lookupSetter__: (...)
			// }
		uni.uploadFile({
			url: baseURL + 'sys/common/upload', // 替换为实际的上传接口地址
			filePath: data,
			name: 'file',
			header: {
				'X-Access-Token': uni.getStorageSync('Token')
			},
			// uni.getStorageSync('Token')?uni.getStorageSync('Token'):
			formData: {
				// 这里可以添加其他表单数据
				// file: res.tempFiles[0],
			},
			success: (uploadRes) => {
				console.log('上传成功', uploadRes);
				// fetchData(uploadRes)

			},
			fail: (err) => {
				console.error('上传失败', err);
			}
		});
	}
	const saveInfoFun = () => {
		if (!nickName.value) {
			uni.showToast({ title: '昵称不能为空', icon: 'none' });
			return;
		}
		// 此处可扩展为调用后端接口保存数据
		console.log('保存的头像:', avatarUrl.value, '昵称:', nickName.value);

		try {

			const data = {
				avatarUrl: avatarUrl.value,
				signature: code.value,
				realname: nickName.value,
				inviteCode: "1"
			}
			console.log(data)
			
			uni.request({
				data: data,
				
				url: 'https://www.mrxc915.com/ai/sys/weCatlogin', // 替换为实际的 API 地址
				
				// url: 'http://121.40.122.64:8183/ai/sys/weCatlogin', // 替换为实际的 API 地址
				
				
				
				method: 'POST',
				success: (res) => {
					popupUseRef.value?.close();
					uni.showTabBar(); // 显示tabbar
					const responses = res.data.result;
					console.log('提交结果:', responses);
					uni.setStorageSync('Token', res.data.result.token);
					// sessionStorage.setItem('Token', res.data.result.token);
					dataInfo.userInfoObj = responses.userInfo


					// dataInfo.userInfoObj.usernames = responses.userInfo.username
					// dataInfo.userInfoObj.username = responses.userInfo.username.substring(0, 5)
					// console.log('responses.userInfo')
					// console.log(dataInfo.userInfoObj)
					store.commit('setIsMember', responses.userInfo.isMember)
					// "isMember":"是否会员  0：不是 1：是",
					store.commit('setisMerchant', responses.userInfo.isMerchant)
					// "isMerchant":"是否商家 0：不是 1：是",
					uni.setStorageSync('userData', JSON.stringify(responses.userInfo));

					listFun()
					getPopularListFun()
				},
				fail: (err) => {
					console.error('请求失败:', err);
				}
			});
			// console.log(data)



		} catch (error) {
			// 处理错误
		}
	}
	const checkTokenExists = () => {
		const token = uni.getStorageSync('Token');
		if (token) {
			console.log('Token 存在:', token);
			return true;
		} else {
			console.log('Token 不存在');
			return false;
		}
	};

	onLoad(() => {


	})
	onMounted(() => {
		const tokenExists = checkTokenExists();
		if (!tokenExists) {

			setTimeout(() => {
				// isPopupVisible.value = true
				uni.hideTabBar(); // 隐藏tabbar
				popupUseRef.value?.open();
			}, 0);
		} else {
			listFun()
			getPopularListFun()
			// 若 Token 不存在，可执行相应操作
		}



	})
	onShow(() => {
		submitData()

	})
</script>
<style lang="scss">
	.gundongtiao{
		::-webkit-scrollbar {
		    width: 0;
		    height: 0;
			 visibility: hidden;
		}
	}
	
</style>
<style scoped lang="scss">
	// @import '/common/css/index.scss';
	.renClass {
		position: absolute;
		right: 0%;
		bottom: 0;
	}

	.renNvClass {
		position: absolute;
		right: -25rpx;
		bottom: 0;
	}

	:deep(.uv-navbar__content) {
		// background-color: transparent !important;
	}

	.itemClass {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		/* 分为三列，每列宽度相等 */
		// grid-template-rows: 100rpx; /* 高度为100rpx */
		gap: 20rpx;
	}

	.info-container {
		padding: 20px;
	}

	.title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.desc {
		color: #666;
		line-height: 1.6;
		margin-bottom: 20px;
	}

	.item {
		margin-bottom: 15px;
		display: flex;
		align-items: center;

	}

	.label {
		width: 50px;
		color: #333;
		font-size: 14px;
	}

	.avatar-container {
		// flex: 1;
		display: flex;
		align-items: center;
		justify-content: start;
	}

	.avatar {
		width: 50px;
		height: 50px;
		border-radius: 50%;
		margin-right: 10px;
	}

	.choose-avatar-btn {
		padding: 0px 16px;

		background-color: #007DF5;
		border: 1px solid #007DF5;
		font-size: 22rpx;
		border-radius: 4px;
		color: #ffffff;
	}

	.nickname-input {
		// flex: 1;
		width: 100%;
		padding: 8px;
		border: 1px solid #ddd;
		border-radius: 4px;
		margin-left: 10px;
	}

	.save-btn {
		width: 100%;
		// padding: 10px;

		background-color: #007DF5;
		border: 1px solid #007DF5;
		border-radius: 4px;
		color: #ffffff;
	}
</style>